package edu.song.yeb.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.song.yeb.boot.config.security.LoginUserService;
import edu.song.yeb.boot.config.util.JwtTokenUtil;
import edu.song.yeb.boot.domain.Admin;
import edu.song.yeb.boot.pojo.RespBean;
import edu.song.yeb.boot.service.AdminService;
import edu.song.yeb.boot.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Resource
    private LoginUserService loginUserService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHeader;

    @Resource
    private  AdminMapper adminMapper;

    @Override
    public RespBean login(String username, String password,String code, HttpServletRequest request) {
        //校验验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        System.err.println("服务器验证码："+captcha);
        System.err.println("用户输入的验证码："+code);
        if(Objects.isNull(captcha) || !captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码错误,请重新输入！");
        }
        UserDetails userDetails = this.loginUserService.loadUserByUsername(username);
        if(Objects.isNull(userDetails) || !this.passwordEncoder.matches(password, userDetails.getPassword()) ){
            return RespBean.error("登录失败，错误的账号或密码！");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("对不起，账号无效！");
        }
        //保存到Spring Security中
        UsernamePasswordAuthenticationToken authentication =new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",this.tokenHeader);
        return RespBean.success("登录成功",map);
    }

    @Override
    public Admin findAdminByUsername(String username) {
        return this.adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }
}




